// $Id$
package com.daikit.daikit4gxt.client.ui.editor.field;

import com.daikit.commons.shared.bean.DkLanguage;
import com.daikit.commons.shared.utils.DkStringUtils;
import com.daikit.daikit4gxt.client.DkCacheEntity;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.http.client.UrlBuilder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.sencha.gxt.data.shared.LabelProvider;


/**
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 */
public class DkLanguageChooserComboBox extends DkComboBox<DkLanguage>
{
	/**
	 * Constructor
	 * 
	 * @param reloadApplicationOnChange
	 *           boolean indicating whether to reload application when comboBox value changes or not
	 * @param availableLocales
	 *           a {@link DkCacheEntity} containing available locales
	 */
	public DkLanguageChooserComboBox(final boolean reloadApplicationOnChange, final DkCacheEntity<DkLanguage> availableLocales)
	{
		super(availableLocales, new LabelProvider<DkLanguage>()
		{
			@Override
			public String getLabel(final DkLanguage item)
			{
				return DkStringUtils.join(item.getIsocode(), item.getLabel());
			}
		});
		if (reloadApplicationOnChange)
		{
			addSelectionHandler(new SelectionHandler<DkLanguage>()
			{
				@Override
				public void onSelection(final SelectionEvent<DkLanguage> selectionEvent)
				{
					reloadApplicationWithLocale(selectionEvent.getSelectedItem());
				}
			});
		}
		setForceSelection(true);
	}

	/**
	 * Method called when user wants to reload the application with another locale
	 * 
	 * @param localeData
	 */
	public void reloadApplicationWithLocale(final DkLanguage localeData)
	{
		if (localeData != null)
		{
			final UrlBuilder builder = Location.createUrlBuilder().setParameter("locale", localeData.getIsocode());
			Window.Location.replace(builder.buildString());
		}
	}
}
